<template>
  <div class="rewelding-frequency">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="出口卷号">
          <el-input v-model="searchForm.extid" placeholder="输入" />
        </el-form-item>
        <el-form-item label="钢种">
          <el-input v-model="searchForm.steelGrade" placeholder="输入" />
        </el-form-item>
        <el-form-item label="班组">
          <el-select v-model="searchForm.crew" placeholder="请选择" style="width: 100px" clearable class="custom-select">
            <el-option label="全部" value="" />
            <el-option label="甲" value="A" />
            <el-option label="乙" value="B" />
            <el-option label="丙" value="C" />
            <el-option label="丁" value="D" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      max-height="390px"
      :header-cell-style="{ background: '#2a5caa', color: '#fff', padding: '8px 10px', textAlign: 'center', fontWeight: 'normal', border: 'none' }"
      :cell-style="{ padding: '8px 10px', textAlign: 'center', color: '#c0c4cc', border: 'none' }"
      :row-style="{ background: '#0f2142' }"
    >
      <el-table-column type="index" label="序号" width="80"  align="center" />
      <el-table-column prop="entID" label="入口卷号"  align="center" />
      <el-table-column prop="extID" label="出口卷号" width="160"  align="center" />
      <el-table-column prop="shift" label="班次"  align="center">
        <template #default="scope">
          <span>{{ scope.row.shift=='1'?'白':'夜' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="crew" label="班组"  align="center">
        <template #default="scope">
          <span>{{ scope.row.crew=='A'?'甲':scope.row.crew=='B'?'乙':scope.row.crew=='C'?'丙':'丁' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="steelGrade" label="钢种"  align="center" />
      <el-table-column prop="inMatThk" label="入口厚度"  align="center" />
      <el-table-column prop="inMatWidth" label="入口宽度"  align="center" />
      <el-table-column prop="outMatThk" label="出口厚度"  align="center" />
      <el-table-column prop="outMatWidth" label="出口宽度"  align="center" />
      <el-table-column prop="exSpeedMax" label="出口段速度最大值[m/min]"  align="center" />
      <el-table-column prop="s5exSpeedL2Set" label="S5出口速度二级设定值[m/min]" width="160"  align="center" />
      <el-table-column prop="s5exSpeedLimit" label="S5出口速度工艺限速[m/min]"  align="center" />
      <el-table-column prop="createTime" label="创建时间" width="160" align="center">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>

      
    </el-table>
    <!-- 分页区域 -->
    <div class="pagination-panel">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>


    <!-- 图表区域 -->
    <div class="charts-container">
      <div class="chart-item">
        <div class="chart-title">按班组统计未达成率</div>
        <div class="chart-wrapper">
          <div ref="crewChartRef" class="chart"></div>
        </div>
      </div>
      <div class="chart-item">
        <div class="chart-title">按钢种统计未达成率</div>
        <div class="chart-wrapper">
          <div ref="steelGradeChartRef" class="chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { acidRollingApi } from '/@/api/acidRollingProductionEfficiency/index';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

// 图表引用
const crewChartRef = ref<HTMLElement>();
const steelGradeChartRef = ref<HTMLElement>();

// 搜索表单数据
const searchForm = reactive({
  extid: "",
  steelGrade:"",
  crew:""
});


// 表格数据
const tableData = ref([
  {
    steelGrade: "",
    inMatThk: "",
    inMatWidth:"",
    outMatWidth: "",
    outMatThk: "",
    crew: "",
    entid: "",
    extid: "",
    createTimes: "",
    shift: "",
    arriveWaitPosTime: "",
    exSpeedMax:"",
    s5exSpeedL2Set:"",
    s5exSpeedLimit:""

  }
  // ... 其他数据
]);

const crewTableData = ref<any[]>([]);
const steelGradeTableData = ref<any[]>([]);

// --- Pagination ---
const pagination = reactive({
  currentPage: 1,
  pageSize: 50,
  total: tableData.value.length
});


// 生命周期钩子
onMounted(async () => {
  fetchTableData();

});

// 搜索方法
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTableData();
};

// 页码变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchTableData();
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchTableData();
};

// 获取表格数据
const fetchTableData = async () => {
  try {
    const params: any = {
      pageIndex: String(pagination.currentPage),
      pageSize: String(pagination.pageSize),
      condition: {
        extid: searchForm.extid,
        steelGrade: searchForm.steelGrade,
        crew:searchForm.crew
      },
      
    };
    
    Object.keys(params).forEach(key => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });
    console.log("params"+params)
    const response = await acidRollingApi.findProSpeedAll(params);
    const responseData = response.data;
    if (
      responseData &&
      responseData.data &&
      Array.isArray(responseData.data)
    ) {
      tableData.value = responseData.data.map((item: any) => ({
        ...item
      }));
      pagination.total = responseData.count || responseData.data.length;
      ElMessage.success(responseData.msg || "查询成功");
      
      // 初始化图表
      initCharts();
    } else {
      ElMessage.info(
        responseData?.msg ||
          (response as any)?.msg ||
          "未查询到数据或响应格式不正确"
      );
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error: any) {
    const errorMessage =
      error.response?.data?.msg ||
      error.data?.msg ||
      error.msg ||
      error.message ||
      "获取数据失败";
    ElMessage.error(errorMessage);
    tableData.value = [];
    pagination.total = 0;
  }
};




// 重置方法
const handleReset = () => {
  searchForm.extid = "";
  searchForm.steelGrade = "";
};

// 新增格式化时间函数
function formatDateTime(dateTime: string | Date | null | undefined): string {
  if (!dateTime) return '-';
  
  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) return '-';
    
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
    const h = String(date.getHours()).padStart(2, '0');
    const min = String(date.getMinutes()).padStart(2, '0');
    const s = String(date.getSeconds()).padStart(2, '0');
    
    return `${y}-${m}-${d} ${h}:${min}:${s}`;
  } catch (error) {
    console.error('时间格式化错误:', error);
    return '-';
  }
}




// 初始化图表
const initCharts = async () => {
  nextTick(async () => {
    // 班组统计图表
    if (crewChartRef.value) {
      const crewChart = echarts.init(crewChartRef.value);
      const crewData = await calculateCrewStatistics();

      console.log("crewData", crewData)
      
      const crewOption = {
        title: {
          text: '按班组统计未达成率',
          textStyle: {
            color: '#c0c4cc',
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: crewData.labels,
          axisLabel: {
            color: '#c0c4cc'
          },
          axisLine: {
            lineStyle: {
              color: '#3a5a8a'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#c0c4cc',
            formatter: '{value}%'
          },
          axisLine: {
            lineStyle: {
              color: '#3a5a8a'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#3a5a8a'
            }
          }
        },
        series: [{
          data: crewData.values,
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2979ff' },
              { offset: 1, color: '#1c2d5a' }
            ])
          }
        }]
      };
      
      crewChart.setOption(crewOption);
    }

    // 钢种统计图表
    if (steelGradeChartRef.value) {
      const steelGradeChart = echarts.init(steelGradeChartRef.value);
      const steelGradeData = await calculateSteelGradeStatistics();
      
      const steelGradeOption = {
        title: {
          text: '按钢种统计未达成率',
          textStyle: {
            color: '#c0c4cc',
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: steelGradeData.labels,
          axisLabel: {
            color: '#c0c4cc',
            rotate: 45
          },
          axisLine: {
            lineStyle: {
              color: '#3a5a8a'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#c0c4cc',
            formatter: '{value}%'
          },
          axisLine: {
            lineStyle: {
              color: '#3a5a8a'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#3a5a8a'
            }
          }
        },
        series: [{
          data: steelGradeData.values,
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#67c23a' },
              { offset: 1, color: '#1c2d5a' }
            ])
          }
        }]
      };
      
      steelGradeChart.setOption(steelGradeOption);
    }
  });
};

// 计算班组统计数据
const calculateCrewStatistics = async () => {
  const crewStats: { [key: string]: { failed: string } } = {};
  const params: any = {};
  const response = await acidRollingApi.findProSpeedStatisticsByShift(params);
  const responseData = response.data;
  if (
    responseData &&
    responseData.data &&
    Array.isArray(responseData.data)
  ) {
    crewTableData.value = responseData.data.map((item: any) => ({
    ...item
    }));

  } else {
    crewTableData.value = [];
  }
  
  crewTableData.value.forEach(item => {
    const crew = item.crew=="A"?"甲":item.crew=="B"?"乙":item.crew=="C"?"丙":"丁" || '未知';
    if (!crewStats[crew]) {
      crewStats[crew] = { failed: "0%" };
    }
    // 假设未达成条件：出口段速度最大值小于S5出口速度二级设定值
    crewStats[crew].failed=(item.belowStandardRate*100).toFixed(2)
  });
  
  const labels = Object.keys(crewStats);
  const values = labels.map(crew => {
    const stats = crewStats[crew];
    return stats.failed;
  });
  
  return { labels, values };
};

// 计算钢种统计数据
const calculateSteelGradeStatistics = async () => {
  const steelGradeStats: { [key: string]: { failed: string } } = {};
  const params: any = {};
  const response = await acidRollingApi.findProSpeedStatisticsBySteelGrade(params);
  const responseData = response.data;
  if (
    responseData &&
    responseData.data &&
    Array.isArray(responseData.data)
  ) {
    steelGradeTableData.value = responseData.data.map((item: any) => ({
      ...item
    }));

  } else {
    steelGradeTableData.value = [];
  }
  
  steelGradeTableData.value.forEach(item => {
    const steelGrade = item.steelGrade || '未知';
    if (!steelGradeStats[steelGrade]) {
      steelGradeStats[steelGrade] = { failed: 0 };
    }
    steelGradeStats[steelGrade].failed = (item.belowStandardRate*100).toFixed(2);
  });
  
  const labels = Object.keys(steelGradeStats);
  const values = labels.map(steelGrade => {
    const stats = steelGradeStats[steelGrade];
    return stats.failed;
  });
  
  return { labels, values };
};

</script>

<style scoped>
.rewelding-frequency {
  background-color: #0a1a3a;
  color: #c0c4cc;
  padding: 10px;
  height: 100%;
  /* Use 100% for layout within router-view */
  box-sizing: border-box;
  font-family: "Microsoft YaHei", "Segoe UI", sans-serif;
  font-size: 13px;
  overflow: hidden;
  scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
  display: flex;
  flex-direction: column;
}

.search-form {
  background-color: #1c2d5a;
  padding: 10px 15px;
  border-radius: 3px;
  flex-shrink: 0;
}

:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  /* Match LayOutJudge */
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

:deep(.el-form-item__label) {
  color: #c0c4cc;
  white-space: nowrap;
  min-width: 65px;
  /* Match LayOutJudge */
  text-align: right;
}

:deep(.el-table__header) th {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-input__wrapper) {
  width: 180px;
}

:deep(.el-date-editor.el-input) {
  width: 180px;
}

:deep(.el-table),
:deep(.el-table__body),
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__empty-block) {
  background: linear-gradient(135deg, #183c7e 0%, #0a1a3a 100%) !important;
}
:deep(.el-table th),
:deep(.el-table td) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr) {
  background-color: #1c2d5a !important;
}
:deep(.el-table__body tr:hover > td) {
  background-color: #223a6b !important;
}

:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__border-left-patch),
:deep(.el-table--border .el-table__inner-wrapper::before) {
  z-index: -1;
}

:deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid #06279d !important;
}
:deep(.el-table--border td.el-table__cell),
:deep(.el-table--border th.el-table__cell) {
  border-right: 1px solid #06279d !important;
  border-bottom: none;
}


:deep(.custom-date-picker.el-date-editor) {
  width: 260px !important;
  /* Match LayOutJudge */
  height: 28px;
  background-color: #0a1a3a;
  border: 1px solid #3a5a8a;
  box-shadow: none;
}

.custom-input,
.custom-select,
.range-input,
:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  height: 28px;
  line-height: 28px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  border-radius: 3px !important;
  color: #c0c4cc !important;
  box-shadow: none !important;
  font-size: 13px !important;
}

:deep(.custom-select .el-select__placeholder),
:deep(.custom-select .el-select__caret) {
  color: #c0c4cc;
}
.rewelding-frequency > *:not(:last-child) {
  margin-bottom: 15px;
}

 .result-ok {
    color: #67c23a;
    /* Green */
    font-weight: bold;
    background-color: rgba(103, 194, 58, 0.1);
    padding: 2px 6px;
    border-radius: 3px;
  }

  .result-no {
    color: #ff4d4f;
    /* Red */
    font-weight: bold;
    background-color: rgba(255, 77, 79, 0.1);
    padding: 2px 6px;
    border-radius: 3px;
  }
  .custom-select {
    width: 70px;
    /* Match LayOutJudge */
  }

  /* --- Pagination Panel (Styles should be consistent) --- */
  .pagination-panel {
    background-color: #1c2d5a;
    padding: 8px 15px;
    border-radius: 3px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 0;
  }
  :deep(.el-pagination) {
    background-color: transparent !important;
  }
  :deep(.el-pagination__total),
  :deep(.el-pagination__sizes),
  :deep(.el-pagination__jump),
  :deep(.el-pagination__editor),
  :deep(.el-pagination button),
  :deep(.el-pager li) {
    background-color: #1c2d5a !important;
    color: #7ec7ff !important;
    border: none !important;
  }
  :deep(.el-pager li.is-active) {
    background-color: #2979ff !important;
    color: #fff !important;
  }

  /* 图表容器样式 */
  .charts-container {
    display: flex;
    gap: 20px;
    margin-top: 20px;
    padding: 15px;
    background-color: #1c2d5a;
    border-radius: 8px;
  }

  .chart-item {
    flex: 1;
    background-color: #0a1a3a;
    border-radius: 6px;
    padding: 15px;
    border: 1px solid #3a5a8a;
  }

  .chart-title {
    color: #c0c4cc;
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 15px;
    text-align: center;
  }

  .chart-wrapper {
    height: 300px;
  }

  .chart {
    width: 100%;
    height: 100%;
  }

</style>

